package cn.gzmli.dtt.common.utils;

import cn.gzmli.dtt.common.entity.PageInfo;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @Descript
 * @Author xsx
 * @Date 2017/12/25
 */
@Service
@Transactional
public class BaseService<T> {
    @Autowired
    private BaseDao<T> baseDao;

    public List<T> getAll() throws Exception {
        return this.baseDao.queryEntityAll();
    }

    public List<T> getByCondition(DetachedCriteria condition, PageInfo pageInfo) throws Exception {
        if (pageInfo.getPageSize()>0){
            return this.baseDao.queryEntityByPage(condition, pageInfo);
        }else{
            return this.baseDao.queryEntity(condition);
        }
    }

    public List<T> getByCondition(DetachedCriteria condition) throws Exception {
        return this.baseDao.queryEntity(condition);
    }

    public T get(Integer id) throws Exception {
        return this.baseDao.get(id);
    }

    public <E> E get(Class<E> cla, Integer id) throws Exception {
        return this.baseDao.get(cla, id);
    }

    public T getByCondition(Map<String, String> condition) throws Exception {
        return this.baseDao.queryOnlyEntity(condition);
    }

    public T save(T t) throws Exception {
        Serializable id = this.baseDao.insert(t);
        Class cla = t.getClass();
        Method method = cla.getMethod("setId", Integer.class);
        method.invoke(t, (Integer) id);
        return t;
    }

    public void update(T t) throws Exception {
        this.baseDao.update(t);
    }

    public void update2(T t) throws Exception {
        this.baseDao.update2(t);
    }

    public void delete(T t) throws Exception {
        this.baseDao.delete(t);
    }

    public void delete2(T t) throws Exception {
        Class cla = t.getClass();
        Method method = cla.getMethod("getId");
        Object id = method.invoke(t);
        StringBuilder sql = new StringBuilder();
        sql.append("DELETE FROM ").append(cla.getSimpleName()).append(" WHERE id=?");
        this.baseDao.getJdbcTemplate().update(sql.toString(), id);
    }

    public BaseDao getDao(){
        return this.baseDao;
    }
}
